﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace XFFSM
{
    public class FSMTransition
    {
        #region 字段
        private FSMTransitionData data;
        private FSMController controller;
        private FSMStateNode toState;
        public List<FSMCondition> conditions;

        #endregion

        #region 属性
        public FSMTransitionData Data => data;

        // 目标状态
        public FSMStateNode ToState => toState;

        // 条件是否已经满足
        public bool IsMeet
        {
            get
            {
                if (conditions.Count == 0) return false;

                // 判断是不是所有的条件都满足了 
                foreach (var item in conditions)
                {
                    if (item.state == ConditionState.NotMeet) return false;
                }

                if (toState == null) { Debug.LogError("查询目标状态失败!"); return false; }

                if (!data.fromStateName.Equals(controller.currentState.data.name))
                {

                    // AnyState
                    if (!data.fromStateName.Equals(FSMConst.anyState)) return false;

                    // 判断当前的状态 跟 目标状态是不是一个 
                    if (controller.currentState.data.name.Equals(data.toStateName)) return false;
                }
                return true;
            }

        }



        #endregion


        public FSMTransition(FSMController controller, FSMTransitionData data) {
            this.data = data;
            this.controller = controller;

            this.conditions = new List<FSMCondition>();

            foreach (var item in this.data.conditions)
            {
                FSMCondition condition = new FSMCondition(item, controller);
                condition.onConditionMeet += this.CheckConditionIsMeet;
                this.conditions.Add(condition);
            }

            if ( controller.states.ContainsKey(data.toStateName) ) {
                toState = controller.states[data.toStateName];
            }

        }

        // 检测条件是不是都满足了
        public void CheckConditionIsMeet() {
            if (IsMeet) {
                // reset trigger
                ResetTrigger();
                // 切换状态 
                controller.SwitchState(toState,this);
            }

        }

        private void ResetTrigger() {
            foreach (var item in conditions)
            {
                if (item.Parameter.parameterType == ParameterType.Trigger)
                    controller.ResetTrigger(item.Parameter.name);
            }
        }

    }

}

